import Auth from './Auth'
import NTPromise from './NTPromise'
/**
 * 这里是防火墙，对所有请求进行拦截，并判断当前是否有权限访问
 */
class Firewall {
  constructor(){
    this.auth = new Auth
    this.promise = new NTPromise
    this.initProtectedResources()
  }

  initProtectedResources() {
    this.protectedRoutes = [
      /^\/api\/my\/(\w)+/
    ]

    this.protectedPages = [
      /^\/pages\/my(\w|[-]|[\/])*/
    ]

    this.tryProtectedPages = [
      /^pages\/homepage*/, /^pages\/feature\/detail*/, /^pages\/favorite\/list*/
    ]
  }
  /**
   * @param url 要访问的url （仅限API请求）
   * @param callback 如果有权限则执行此回调
   */
  async access(url= ''){
    if(!url){
      url = this.getCurrentPageUrl()
    }
    let routes = this.protectedRoutes
    for (let i = 0; i < routes.length; i++){
      if(routes[i].test(url)){
        console.log('authenticate url ：', url)
        let authed = await this.auth.authenticate('url')
        console.log('access authed : ', authed)
        return authed
      }
    }
    
    return true
  }
  tryVisit(url = '', callback) {
    let pages = this.tryProtectedPages
    if(!url){
      url = this.getCurrentPageUrl()
    }
    for (let i = 0; i < pages.length; i++) {
      if (pages[i].test(url)) {
        console.log('authenticate',url)
        this.auth.authenticate('try_page', callback)
        return
      }
    }
    callback && callback()
  }
  /**
   * @param url
   * @param gotoType 可选值：self表示自身，不需要跳转；navigate表示跳转；redirect表示重定向
   */
  async visit(url, gotoType, callback){
    let result = await new Promise((resolve, reject) => {
      let pages = this.protectedPages
      let called = false
      for (let i = 0; i < pages.length; i++) {
        if (pages[i].test(url)) {
          called = true
          this.auth.authenticate('page', () => {
            if (gotoType == 'navigate') {
              wx.navigateTo({
                url: url
              })
            } else if (gotoType == 'redirect') {
              wx.redirectTo({
                url: url,
              })
            } else {
              resolve(true)
            }
          })
          break
        }
      }
      if (!called) {
        if (gotoType == 'navigate') {
          wx.navigateTo({
            url: url
          })
        } else if (gotoType == 'redirect') {
          wx.redirectTo({
            url: url,
          })
        }
      }
    })

    if (result) {
      callback && callback()
    }
  }

  getCurrentPageUrl(){
    let pages = getCurrentPages()    //获取加载的页面
    let currentPage = pages[pages.length-1]    //获取当前页面的对象
    let url = currentPage.route    //当前页面url
    return url
  }

}

export default Firewall
